package abacab.serialization.huffman;

import java.io.IOException;
import java.io.OutputStream;

/**
 * The encoding context
 */
public class EncodingContext {
	/** The output stream */
	private final OutputStream	outputStream;

	/** The currently written byte */
	private int									currentByte;

	/** The number of bits remaining before the current byte is completed */
	private int									bitsRemaining;

	/**
	 * Create the encoding context
	 * 
	 * @param outputStream
	 *          the output stream
	 */
	public EncodingContext(OutputStream outputStream) {
		this.outputStream = outputStream;
		this.bitsRemaining = 8;
	}

	/**
	 * @return the output stream
	 */
	public final OutputStream getOutputStream() {
		return this.outputStream;
	}

	/**
	 * @return the currently written byte
	 */
	public final int getCurrentByte() {
		return this.currentByte;
	}

	/**
	 * Update the current byte
	 * 
	 * @param mask
	 *          the mask to use
	 */
	public void updateCurrentByte(int mask) {
		this.currentByte |= mask;
	}

	/**
	 * Reset the current byte
	 * 
	 * @throws IOException
	 *           if an error occurred
	 */
	public final void commitCurrentByte() throws IOException {
		this.outputStream.write(this.currentByte);
		this.currentByte = 0;
		this.bitsRemaining = 8;
	}

	/**
	 * @param bitsRemaining
	 *          the number of bits remaining before the current byte is completed
	 */
	public final void setBitsRemaining(int bitsRemaining) {
		this.bitsRemaining = bitsRemaining;
	}

	/**
	 * @return the number of bits remaining before the current byte is completed
	 */
	public final int getBitsRemaining() {
		return this.bitsRemaining;
	}
}